<template>
  <el-dialog
    :title="formData.id?'修改角色':'添加角色'"
    :visible.sync="dialogVisible"
    width="50%"
    @close="closeHanlder"
  >
    <el-form label-width="100px" ref="form" :model="formData" :rules="formRules">
      <el-form-item prop="role_name" label="角色名称">
        <el-input placeholder="请输入角色名称" v-model="formData.role_name"></el-input>
      </el-form-item>
      <el-form-item prop="identify" label="角色标识">
        <el-input placeholder="请输入角色标识" v-model="formData.identify"></el-input>
      </el-form-item>
      <el-form-item prop="description" label="角色描述">
        <el-input placeholder="请输入角色描述" v-model="formData.description"></el-input>
      </el-form-item>
      <el-form-item prop="permission_name" label="角色权限">
        <el-tree
          ref="tree"
          v-if="dialogVisible"
          :data="allAuth"
          show-checkbox
          :default-checked-keys="formData.authlist"
          node-key="id"
          :props="{label:'permission_name'}"
        ></el-tree>
      </el-form-item>
      <br />
      <el-row type="flex" justify="center">
        <!--  // 4 事件提交逻辑 【新增功能】 -->
        <el-button @click="dialogVisible=false" size="small">取消</el-button>
        <el-button type="primary" size="small" @click="addFn">确定</el-button>
      </el-row>
    </el-form>
  </el-dialog>
</template>

<script>
import {
  addRoleListApi,
  editRoleApi,
  getRoleInfoApi
} from "@/api/permission/role";

export default {
  name: "RoleTools",
  components: {},
  props: {},
  data() {
    return {
      formData: {
        role_name: "",
        identify: "",
        description: "",
        authlist: []
      },
      dialogVisible: false,
      allAuth: [], //所有权限
      //存储树的id
      formRules: {
        role_name: [{ required: true, message: "必须!", trigger: "blur" }],
        identify: [{ required: true, message: "必须!", trigger: "blur" }],
        description: [{ required: true, message: "必须!", trigger: "blur" }],
        authlist: [{ required: true, message: "请勾选!", trigger: "blur" }]
      }
    };
  },
  computed: {},
  watch: {},
  created() {
    this.initData();
  },
  mounted() {},
  methods: {
    async initData() {
      let res = await getRoleInfoApi();
      // console.log(res);
      this.allAuth = res;
    },
    async addFn() {
      //校验
      try {
        await this.$refs.form.validate();
      } catch (error) {
        console.log(error);
      }
      const permIds = this.$refs.tree.getCheckedKeys();
      // console.log(permIds);
      this.formData.authlist = permIds;
      if (permIds.length === 0) return this.$message.error("请勾选");

      //发送请求
      if (this.formData.id) {
        await editRoleApi(this.formData); //修改请求
      } else {
        await addRoleListApi(this.formData); //添加请求
      }

      this.$message.success("操作成功");
      this.$emit("updateList");
      this.dialogVisible = false;
    },
    closeHanlder() {
      this.formData = {};
    }
  }
};
</script>
<style lang="less" scoped>
</style>